package org.wenhuayuan.uilibrary.tab.bottom;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import org.wenhuayuan.hiapplib.util.HiDisplayUtil;
import org.wenhuayuan.hiapplib.util.HiViewUtil;
import org.wenhuayuan.uilibrary.R;
import org.wenhuayuan.uilibrary.tab.common.IHiTabLayout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class HiTabBottomLayout extends FrameLayout implements IHiTabLayout<HiTabBottom, HiTabBottomInfo<?>> {
    private List<OnTabSelectedListener<HiTabBottomInfo<?>>> tabSelectedListeners = new ArrayList<>();
    private HiTabBottomInfo<?> preSelectedInfo;  // 记录已被选中的tab，该tab属于当前点击事件的上一个点击事件
    private float bottomAlpha = 1f; // 底部透明度
    private static float tabBottomHeight = 50f; // 底部高度
    private float bottomLineHeight = 0.5f; // 底部上分割线高度
    private String bottomLineColor = "#dfe0e1";// 底部上分割线颜色
    private List<HiTabBottomInfo<?>> infoList; // 底部按钮数据
    private String TAG = "FRAME_LAYOUT_TAG";
    private static Context context;
    public HiTabBottomLayout(@NonNull Context context) {
        this(context, null);
    }

    public HiTabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HiTabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        this.init();
    }

    @Override
    public HiTabBottom findTab(@NonNull HiTabBottomInfo<?> info) {
        ViewGroup frameLayout = findViewWithTag(TAG);
        for (int i = 0; i < frameLayout.getChildCount(); i ++) {
            View child = frameLayout.getChildAt(i);
            if (child instanceof HiTabBottom) {
                HiTabBottom tabBottom = (HiTabBottom)child;
                if(tabBottom.getTabInfo() == info) {
                    return tabBottom;
                }
            }
        }
        return null;
    }

    @Override
    public void addTabSelectedChangeListener(OnTabSelectedListener<HiTabBottomInfo<?>> listener) {
        tabSelectedListeners.add(listener);
    }

    @Override
    public void defaultSelected(@NonNull HiTabBottomInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    @Override
    public void inflateInfo(@NonNull List<HiTabBottomInfo<?>> infoList) {
        if (infoList.isEmpty()) return;
        this.infoList = infoList;
        // 移除已经添加的tab-view
        // 移除方式，从后向前进行移除
        for (int i = getChildCount() - 1; i > 0; i --) {
            removeViewAt(i);
        }
        preSelectedInfo = null;
        addBackGround();//添加背景色
        // 清除已经添加过的HiTabBottom的监听
        // 在使用remove时，会出现一边循环一边删除的问题。解决方式从后向前删或者使用Iterator迭代器遍历
        Iterator<OnTabSelectedListener<HiTabBottomInfo<?>>> iterator = tabSelectedListeners.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() instanceof HiTabBottom) {
                iterator.remove();
            }
        }

        // ----------开始添加tab 且先将tab放到FrameLayout容器中--------------
        FrameLayout frameLayout = new FrameLayout(getContext());
        frameLayout.setTag(TAG);
        // 配置单个tab的高度
        int height = HiDisplayUtil.dp2px(tabBottomHeight, getResources());
        // 获取单个tab的宽度
        int width = HiDisplayUtil.getDisplayWidthInPx(getContext())/infoList.size();
        for (int i = 0; i < infoList.size(); i ++) {
            final HiTabBottomInfo<?> info = infoList.get(i);
            LayoutParams params = new LayoutParams(width, height);
            params.gravity = Gravity.BOTTOM;
            params.leftMargin = i * width;
            HiTabBottom tabBottom = new HiTabBottom(getContext());
            tabSelectedListeners.add(tabBottom);
            tabBottom.setHiTabInfo(info);
            frameLayout.addView(tabBottom, params);

            tabBottom.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    onSelected(info);
                }
            });
        }

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM;
        addBottomLine(); // 添加分割线
        addView(frameLayout, params);
        fixContentView(); // 设置列表view距离底部的距离
    }

    private void onSelected(@NonNull HiTabBottomInfo<?> curSelectedInfo) {
        for (OnTabSelectedListener listener : tabSelectedListeners) {
            // 第一次preSelectedInfo会为null
            listener.onTabSelectedChange(infoList.indexOf(curSelectedInfo), preSelectedInfo, curSelectedInfo);
        }
        this.preSelectedInfo = curSelectedInfo;
    }
    private void addBottomLine() {
        View line = new View(getContext());
        line.setBackgroundColor(Color.parseColor(bottomLineColor));
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, HiDisplayUtil.dp2px(bottomLineHeight, getResources()));
        params.gravity = Gravity.BOTTOM;
        params.bottomMargin = HiDisplayUtil.dp2px(tabBottomHeight - bottomLineHeight, getResources());
        addView(line, params);
        line.setAlpha(bottomAlpha);
    }

    private void init() {

    }
    // 添加背景色
    private void addBackGround() {
        View viewBg = LayoutInflater.from(getContext()).inflate(R.layout.hi_bottom_layout_bg, null);
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, HiDisplayUtil.dp2px(tabBottomHeight, getResources()));
        params.gravity = Gravity.BOTTOM;
        addView(viewBg, params);
        viewBg.setAlpha(bottomAlpha);
    }

    public void setTabBottomAlpha(float bottomAlpha) {
        this.bottomAlpha = bottomAlpha;
    }

    public void setTabBottomHeight(float tabBottomHeight) {
        this.tabBottomHeight = tabBottomHeight;
    }

    public void setTabBottomLineHeight(float bottomLineHeight) {
        this.bottomLineHeight = bottomLineHeight;
    }

    public void setTabBottomLineColor(String bottomLineColor) {
        this.bottomLineColor = bottomLineColor;
    }
    /** 设置列表view距离底部的距离  */
    private void  fixContentView() {
        if (!(getChildAt(0) instanceof ViewGroup)) {
            return;
        }

        ViewGroup rootView = (ViewGroup) getChildAt(0);
        ViewGroup targetView = HiViewUtil.findTypeView(rootView, RecyclerView.class);
        if (null == targetView) {
            targetView = HiViewUtil.findTypeView(rootView, ScrollView.class);
        }
        if (null == targetView) {
            targetView = HiViewUtil.findTypeView(rootView, AbsListView.class);
        }
        if (null != targetView) {
            targetView.setPadding(0, 0, 0, HiDisplayUtil.dp2px(tabBottomHeight, getResources()));
            targetView.setClipToPadding(false);// false-padding的这个绘制区域，会植入到targetView中。
        }
    }

    public static void clipBottomPadding(ViewGroup targetView) {
        if (null != targetView) {
            targetView.setPadding(0, 0, 0, HiDisplayUtil.dp2px(tabBottomHeight, context.getResources()));
            targetView.setClipToPadding(false);// false-padding的这个绘制区域，会植入到targetView中。
        }
    }
}
